package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //校验数据合法性
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"数据不能为空");
        }
        //查询对应的用户是否存在
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.<AdUser>lambdaQuery();
        AdUser user = this.getOne(wrapper.eq(AdUser::getName, dto.getName()));
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不存在");
        }
        //判断密码是否正确
        //首先获取当前对象的盐,拼接上输入的密码在进行MD5加密后,进行对比
        String password = DigestUtils.md5DigestAsHex((dto.getPassword()+user.getSalt()).getBytes());
        if (!password.equals(user.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }

        //密码正确,修改登录时间
        user.setLoginTime(new Date());
        updateById(user);
        //5 颁发token jwt 令牌
        String token = AppJwtUtil.getToken(user.getId().longValue());
        // 用户信息返回 VO
        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(user, userVO);
        //6 返回结果（jwt）
        Map map = new HashMap();
        map.put("token", token);
        map.put("user", userVO);
        return ResponseResult.okResult(map);
    }
}